package cn.cdeden.knowledge.controller.Individual;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.knowledge.domain.AnalysisData;
import cn.cdeden.system.api.RemoteDifyService;
import cn.cdeden.system.api.domain.bo.RemoteDifyKnowledgeBaseBo;
import cn.cdeden.system.api.domain.vo.RemoteDifyKnowledgeBaseCreateVo;
import cn.cdeden.knowledge.domain.EnterpriseFilesTree;
import cn.cdeden.knowledge.domain.dto.EnterpriseFilesTreeDto;
import cn.cdeden.knowledge.domain.dto.EnterpriseFilesTreeQueryParam;
import cn.cdeden.knowledge.domain.dto.FilesTreeTop;
import cn.cdeden.knowledge.enums.TeamFilesTreeRenameParam;
import cn.cdeden.knowledge.service.EnterpriseFilesTreeService;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import io.undertow.util.BadRequestException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业文档树管理
 */
@Controller
@Slf4j
@RestController
@RequiredArgsConstructor
    @RequestMapping("/enterpriseFilesTree")
public class EnterpriseFilesTreeController {

    private final EnterpriseFilesTreeService enterpriseFilesTreeService;

    @DubboReference(check = false,timeout = 6000)
    private final RemoteDifyService remoteDifyService;

    private static final String JSON_MEDIA_TYPE = "application/json";
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String CONTENT_TYPE_HEADER = "Content-Type";
    private static final String BEARER_PREFIX = "Bearer ";

    /**
     *查询企业文档数
     * @param query
     * @param pageable
     * @return
     * @throws BadRequestException
     */
    @GetMapping(value = "/queryTree")
    @ResponseBody
    public R<EnterpriseFilesTreeDto> queryTree(EnterpriseFilesTreeQueryParam query, Pageable pageable) throws BadRequestException {
        EnterpriseFilesTreeDto enterpriseFilesTreeDto = enterpriseFilesTreeService.queryList(query, true);
        return R.ok(enterpriseFilesTreeDto);
    }

    @GetMapping(value = "/queryTreeFreePerm")
    @ResponseBody
    public R<EnterpriseFilesTreeDto> queryTreeFreePerm(EnterpriseFilesTreeQueryParam query, Pageable pageable) throws BadRequestException {
        EnterpriseFilesTreeDto enterpriseFilesTreeDto = enterpriseFilesTreeService.queryList(query, false);
        return R.ok(enterpriseFilesTreeDto);
    }


    /**
     * 查询企业文档树(分页)
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping(value = "/queryPaging")
    @ResponseBody
    public R<TableDataInfo<EnterpriseFilesTreeDto>> queryPaging(EnterpriseFilesTreeQueryParam query, Pageable pageable) {
        TableDataInfo<EnterpriseFilesTreeDto> info = enterpriseFilesTreeService.queryAll(query, pageable);
        return R.ok(info);
    }


    /**
     * 新增企业文档文件夹
     * @param resources
     * @return
     */
    @PostMapping(value = "/addFolder")
    @ResponseBody
    public R<EnterpriseFilesTreeDto> create(@RequestBody EnterpriseFilesTreeDto resources) throws BadRequestException {
//        EnterpriseFilesTreeDto enterpriseFilesTreeDto = enterpriseFilesTreeService.insertData(resources, true);
        EnterpriseFilesTreeDto enterpriseFilesTreeDto = enterpriseFilesTreeService.insertData(resources, true);
        enterpriseFilesTreeService.createFileToEs(enterpriseFilesTreeDto.getId());
        return R.ok(enterpriseFilesTreeDto);
    }

    @PostMapping(value = "/toDify")
    public R toDify(@RequestBody EnterpriseFilesTreeDto enterpriseFilesTreeDto){
        enterpriseFilesTreeService.toDify(enterpriseFilesTreeDto.getIds());
        return R.ok();
    }

    /**
     * 查询企业文档树
     * @param query
     * @return
     */
    @GetMapping(value = "/query")
    @ResponseBody
    public R query(EnterpriseFilesTreeQueryParam query) {
        return R.ok(enterpriseFilesTreeService.queryAll(query,true));
    }



    /**
     * 新增置顶
     * @param top
     * @return
     */
    @PostMapping(value = "/top")
    public R insertTopMark(@RequestBody FilesTreeTop top) throws BadRequestException {
        enterpriseFilesTreeService.topMark(top);
        return R.ok();
    }

    /**
     *企业文件夹重命名
     * @param teamFilesTreeRenameParam
     * @return
     */
    @PostMapping(value = "/rename")
    @ResponseBody
    public R rename(@Valid @RequestBody TeamFilesTreeRenameParam teamFilesTreeRenameParam) throws BadRequestException {
        enterpriseFilesTreeService.rechristen(teamFilesTreeRenameParam);
        return R.ok();
    }


    @GetMapping(value = "/queryAll")
    @ResponseBody
    public R queryAll(EnterpriseFilesTreeQueryParam query) {
        return R.ok(enterpriseFilesTreeService.queryAll(query,false));
    }


    /**
     * 新增描述
     */
    @PostMapping(value = "/updateRemarks")
    public R insertRemarks(@RequestBody EnterpriseFilesTreeDto enterpriseFilesTreeDto){
        enterpriseFilesTreeService.insertRemark(enterpriseFilesTreeDto.getId(), enterpriseFilesTreeDto.getRemarks());
        return R.ok();
    }


    /**
     * 查询知识库
     * @param query
     * @return
     */
    @GetMapping(value = "/queryKnowLab")
    public R queryKnowLab(EnterpriseFilesTreeQueryParam query){
        return R.ok(enterpriseFilesTreeService.queryKnowLab(query,true));
    }


    @GetMapping(value = "/queryAllKnowLab")
    public R queryAllKnowLab(){
        return R.ok(enterpriseFilesTreeService.queryKnowLab());
    }
    /**
     * 新建知识库
     * @param resources
     * @return
     */
    @PostMapping(value = "/newBuiltKnowLab")
    public R newBuiltKnowLab(@RequestBody EnterpriseFilesTreeDto resources){
        String kownLabId = null;
        if (resources.getIsKnowledge()){
            RemoteDifyKnowledgeBaseBo remoteDifyKnowledgeBaseBo = new RemoteDifyKnowledgeBaseBo();
            remoteDifyKnowledgeBaseBo.setName(resources.getRealName());
            remoteDifyKnowledgeBaseBo.setDescription(resources.getRemarks());
            remoteDifyKnowledgeBaseBo.setPermission("all_team_members");
            remoteDifyKnowledgeBaseBo.setIndexing_technique("high_quality");
            try {
                RemoteDifyKnowledgeBaseCreateVo remoteDifyKnowledgeBaseCreateVo = remoteDifyService.create(remoteDifyKnowledgeBaseBo);
                kownLabId = remoteDifyKnowledgeBaseCreateVo.getId();
            }catch (Exception e){
                throw new RuntimeException("网络或问答知识库名称重复，创建问答知识库失败！");
            }
            if (StringUtils.isNullOrBlank(kownLabId)) throw new RuntimeException("创建问答知识库失败！");
        }
        Boolean flag = enterpriseFilesTreeService.newBuiltKnowLab(resources.getClassify(), resources.getRealName(), resources.getRemarks(), resources.getImageUrl(), kownLabId,resources.getTemplateId(),resources.getLocation(),resources.getSort());
        return R.ok();
    }


    /**
     * 编辑知识库
     * @param resources
     * @return
     */
    @PostMapping(value = "/editKnowLab")
    public R editKnowLab(@RequestBody EnterpriseFilesTreeDto resources) {
        enterpriseFilesTreeService.editKnowLab(resources.getId(),resources.getRealName(),resources.getClassify(),resources.getRemarks(),resources.getImageUrl(),resources.getLocation(),resources.getSort());

        return R.ok();
    }

    /**
     * 删除知识库
     * @param resources
     * @return
     */
    @PostMapping(value = "/deleteKnowLab")
    public R deleteKnowLab(@RequestBody EnterpriseFilesTreeDto resources) {
        enterpriseFilesTreeService.deleteKnowLab(resources.getId());

        if (false){
            EnterpriseFilesTree byId = enterpriseFilesTreeService.getById(resources.getId());
            String key = "knowledge";
            Map<String, String> headers = new HashMap<>();
            headers.put(AUTHORIZATION_HEADER, BEARER_PREFIX + key);
            headers.put(CONTENT_TYPE_HEADER, "application/json");
            String url = "http://192.168.6.59/v1/datasets/{"+byId.getId()+"}";
            HttpResponse execute = HttpUtil.createPost(url).addHeaders(headers).execute();
        }
        return R.ok();
    }
    @GetMapping(value = "/isKnowLab")
    public R deleteKnowLab(@RequestParam Long baseId) {
        EnterpriseFilesTree byId = enterpriseFilesTreeService.getById(baseId);
        String aiDatasetId = byId.getAiDatasetId();
        Boolean isKnowLab = false;
        if (!StringUtils.isNullOrBlank(aiDatasetId))isKnowLab = true;
        return R.ok(isKnowLab);
    }

    /**
     * 分析数据
     * @return
     */
    @GetMapping(value = "/analysisData")
    public R analysisData(){
        List<AnalysisData> analysisData = enterpriseFilesTreeService.analysisKnowLab();
        return R.ok(analysisData);
    }

    /**
     * 常用知识库查询
     */
    @GetMapping(value = "/queryCommonKnowLab")
    public R queryCommonKnowLab(Pageable pageable){
        TableDataInfo<EnterpriseFilesTreeDto> enterpriseFilesTreeDtoTableDataInfo = enterpriseFilesTreeService.commonAnalysisKnowLab(pageable);
        return R.ok(enterpriseFilesTreeDtoTableDataInfo);
    }

    @GetMapping(value = "/addViews")
    public R addViews(@RequestParam Long id) {
        EnterpriseFilesTree byId = enterpriseFilesTreeService.getById(id);
        enterpriseFilesTreeService.lambdaUpdate().eq(EnterpriseFilesTree::getId,id).set(EnterpriseFilesTree::getViews,byId.getViews()+1).update();
        return R.ok();
    }

    @PostMapping(value = "/updateAiFiles")
    public R updateAiFiles(@RequestBody EnterpriseFilesTreeDto enterpriseFilesTreeDto){
        List<Long> ids = enterpriseFilesTreeDto.getIds();
        ArrayList<Long> longs = new ArrayList<>();
        for (Long id : ids) {
            EnterpriseFilesTree byId = enterpriseFilesTreeService.getById(id);
            if (byId.getType().equals("folder")) {
                List<EnterpriseFilesTree> list = enterpriseFilesTreeService.lambdaQuery().eq(EnterpriseFilesTree::getParentId, byId.getId()).isNull(EnterpriseFilesTree::getDeleteType).list();
                List<Long> list1 = list.stream().map(EnterpriseFilesTree::getId).toList();
                longs.addAll(list1);
            } else if (byId.getType().equals("file")) {
                longs.add(byId.getId());
            }
        }
        enterpriseFilesTreeService.updateDify(ids);
        return R.ok();
    }
}
